<?php

namespace app\admin\controller;

use DateTime;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Queue;

class Manage extends Common
{
    /**
     * 列表示例
     * */
    public function listDemo()
    {
        $list = Db::name('menu')->paginate(2);
        $this->assign('list', $list);

        $this->assign('title', '列表示例');
        return $this->fetch();
    }

    /**
     * 列表导出示例
     * */
    public function exportListDemo()
    {
        $title = '文件名';
        $th = ['标题一', '标题二', '标题三'];
        $td = ['key1', 'key2', 'key3'];
        $data = [
            [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ], [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ]
        ];

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 表单示例
     * */
    public function formDemo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            echo "<pre>";
            print_r($input);
            exit;
        }
        $this->assign('title', '表单示例');
        return $this->fetch();
    }

    /**
     * 视频分片上传示例
     * */
    public function uploadVideo()
    {
        $this->assign('title', '视频分片上传示例');
        return $this->fetch();
    }

    /**
     * 统计图示例
     * */
    public function chartDemo()
    {
        $this->assign('title', '统计图');
        return $this->fetch();
    }

    /**
     * 树形列表示例
     * */
    public function treeDemo()
    {
        return $this->fetch();
    }

    /**
     * 树状图原始demo
     * */
    public function tree()
    {
        $this->assign('title', 'test');
        return $this->fetch();
    }

    /**
     * iconfont
     * */
    public function iconfont()
    {
        $this->assign('title', 'iconfont');
        return $this->fetch();
    }


    /**
     * 用户列表
     * */
    public function userList()
    {
        $input = Request()->param();

        $mobile = $input['mobile'] ? : '';
        $up_user_id = $input['up_user_id'] ? : 0;

        $where['user_type'] = 3;
        if ($mobile) $where['mobile'] = ['LIKE', "%{$mobile}%"];
        if ($up_user_id) $where['up_user_id'] = $up_user_id;

        $list = Db::name('user')->where($where)->order('id desc')->paginate();

        $spread_user_list = Db::name('user')->where(['user_type' => 1, 'status' => 1])->select();
        $this->assign('spread_user_list', $spread_user_list);

        $this->assign('list', $list);
        return $this->view->fetch();
    }

    /**
     * 启用/禁用
     * */
    public function doUserStatus()
    {
        $id = Request()->param('id');
        $status = Request()->param('status');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('user')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('user')->where(['id' => $id])->setField('status', $status);
            if ($res) {
                adminReturn(1, '操作成功', url('userList'));
            } else {
                adminReturn(2, '操作失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 账号列表
     * */
    public function managerList()
    {
        $input = Request()->param();

        $user_type = $input['user_type'] ? : 0;

        $where = ['user_type' => ['IN', [1, 2]], 'id' => ['gt', 1]];

        if ($user_type) $where['user_type'] = $user_type;

        $list = Db::name('user')->where($where)->order('id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '账号列表');
        return $this->view->fetch();
    }

    /**
     * 生成APP推广海报
     * */
    public function createAppPoster()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '用户ID缺失');

        $path = createPoster($id);
        if ($path) {
            $data = [
                'app_poster' => $path,
                'update_time' => time()
            ];
            $res = Db::name('user')->where('id', $id)->update($data);
            if ($res) {
                adminReturn(1, '操作成功');
            } else {
                adminReturn(2, '操作失败');
            }
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 启用/禁用
     * */
    public function doManagerStatus()
    {
        $id = Request()->param('id');
        $status = Request()->param('status');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('user')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('user')->where(['id' => $id])->setField('status', $status);
            if ($res) {
                adminReturn(1, '操作成功', url('managerList'));
            } else {
                adminReturn(2, '操作失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }


    /**
     * 新增/编辑 账号
     * */
    public function doManager()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'] ? : 0;
            $username = $input['username'];
            $account = $input['account'];
            $user_type = $input['user_type'];
            $password = $input['password'];
            $re_password = $input['re_password'];

            if (empty($username)) adminReturn(2, '请输入名称');
            if (empty($account)) adminReturn(2, '请输入账号');
            if (!$id && ($user_type != 1 && $user_type != 2)) adminReturn(2, '请选账号类型');
            if ($id == 0) {
                if (empty($password)) adminReturn(2, '请输入密码');
                if (empty($re_password)) adminReturn(2, '请输入确认密码');
                if (strlen($password) < 6) apiReturn(2, '密码长度至少6位');
                if ($password !== $re_password) adminReturn(2, '两次密码不一致，请重新输入');
            }

            if ($id) $where['id'] = ['neq', $id];
            $where['account'] = $account;
            $where['is_admin'] = 1;

            $count = Db::name('user')->where($where)->count();
            if ($count) adminReturn(2, '账号已存在');

            Db::startTrans();
            try {
                if ($id) {
                    $data = [
                        'username' => $username,
                        'account' => $account,
                        'password' => thinkEncrypt($password),
                        'update_time' => time()
                    ];

                    $res = Db::name('user')->where(['id' => $id])->update($data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '编辑失败');
                    }
                } else {
                    $data = [
                        'account' => $account,
                        'username' => $username,
                        'user_type' => $user_type,
                        'password' => thinkEncrypt($password),
                        'status' => 1,
                        'is_admin' => 1,
                        'create_time' => time()
                    ];
                    if ($user_type == 2) $data['code'] = createSpreadCode();
                    $user_id = Db::name('user')->insertGetId($data);

                    if (!$user_id) {
                        Db::rollback();
                        adminReturn(2, '新增失败');
                    }

                    $auth_data = [
                        'uid' => $user_id,
                        'group_id' => $user_type == 1 ? 1 : 2
                    ];
                    $res = Db::name('auth_group_access')->insert($auth_data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '新增失败');
                    }
                }

                Db::commit();
                adminReturn(1, '操作成功', url('managerList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败' . $e);
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('user')->where(['id' => $id])->find();

            $this->assign('info', $info);

            $this->assign('title', ($id ? '编辑' : '新增') . '管理员');

            return $this->view->fetch();
        }
    }

    /**
     * 删除管理员
     * */
    public function delManager()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('user')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $res = Db::name('user')->where(['id' => $id])->delete();
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '删除失败');
                }

                $res = Db::name('auth_group_access')->where(['uid' => $id])->delete();
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '删除失败');
                }

                Db::commit();
                adminReturn(1, '删除成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * banner列表
     */
    public function bannerList()
    {
        $list = Db::name('banner')->paginate()->each(function ($v) {
            $title = Db::name('article')->where(['id' => $v['to_id']])->value('title');
            $v['title'] = $title ? : '';
            return $v;
        });

        $this->assign('list', $list);
        $this->assign('title', 'banner列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 banner
     * */
    public function doBanner()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $to_id = $input['to_id'] ? : 0;

            if (empty($img)) adminReturn(2, '请上传banner图');

            $data = [
                "img" => $img,
                "to_id" => $to_id,
            ];

            if ($id > 0) {
                $res = Db::name('banner')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '编辑banner失败或未编辑');
                }
            } else {
                $res = Db::name('banner')->insert($data);
                if ($res) {
                    adminReturn(1, '新增banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '新增banner失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('banner')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . 'banner');

            $article_list = Db::name('article')->field('id,title')->order('id desc')->select();
            $this->assign('article_list', $article_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除banner
     * */
    public function delBanner()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'bannerID缺失');

        $info = Db::name('banner')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('banner')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 审核列表
     * */
    public function identList()
    {
        $input = Request()->param();

        $status = $input['status'] ? : 0;

        $where = [];
        if ($status) $where['status'] = $status;

        $list = Db::name('user_ident')->where($where)->order('id desc')->paginate();
        $this->assign('list', $list);
        return $this->view->fetch();
    }

    /**
     * 通过
     * */
    public function identAgree()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('user_ident')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $data = [
                    'status' => 2,
                    'remark' => '',
                    'update_time' => time()
                ];
                $res = Db::name('user_ident')->where(['id' => $id])->update($data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                $msg_data = insertMsgData($info['user_id'], 'user_ident_agree');
                $res = Db::name('msg')->insert($msg_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                $log_data = [
                    'ident_id' => $id,
                    'username' => $info['username'],
                    'mobile' => $info['mobile'],
                    'id_card' => $info['id_card'],
                    'driver_license' => $info['driver_license'],
                    'card_z' => $info['card_z'],
                    'card_f' => $info['card_f'],
                    'status' => 2,
                    'create_time' => time()
                ];
                $res = Db::name('user_ident_log')->insert($log_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                Db::commit();
                adminReturn(1, '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 审核驳回
     * */
    public function identRefuse()
    {
        $id = Request()->param('id');
        $remark = Request()->param('remark');

        if (empty($id)) adminReturn(2, 'ID缺失');
        if (empty($remark)) adminReturn(2, '请填写驳回理由');

        $info = Db::name('user_ident')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $data = [
                    'status' => 3,
                    'remark' => $remark,
                    'update_time' => time()
                ];
                $res = Db::name('user_ident')->where(['id' => $id])->update($data);
                if (!$res) {
                    adminReturn(2, '操作失败');
                }

                $msg_data = insertMsgData($info['user_id'], 'user_ident_refuse', ['remark' => $remark]);
                $res = Db::name('msg')->insert($msg_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                $log_data = [
                    'ident_id' => $id,
                    'username' => $info['username'],
                    'mobile' => $info['mobile'],
                    'id_card' => $info['id_card'],
                    'driver_license' => $info['driver_license'],
                    'card_z' => $info['card_z'],
                    'card_f' => $info['card_f'],
                    'status' => 3,
                    'remark' => $remark,
                    'create_time' => time()
                ];
                $res = Db::name('user_ident_log')->insert($log_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                Db::commit();
                adminReturn(1, '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }

        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 审核记录
     * */
    public function identLogList()
    {
        $list = Db::name('user_ident_log')->order('id desc')->paginate();

        $this->assign('list', $list);
        return $this->view->fetch();
    }

    /**
     * 车辆列表
     * */
    public function carList()
    {
        $list = Db::name('car')->order('id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '车辆列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 车辆
     * */
    public function doCar()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $number = $input["number"];
            $model = $input["model"];
            $price = $input["price"];

            if (empty($img)) adminReturn(2, '请上传图片');
            if (empty($number)) adminReturn(2, '请输入车牌号');
            if (empty($model)) adminReturn(2, '请输入车型');
            if (empty($price)) adminReturn(2, '请输入日租金');

            $count_where['number'] = $number;
            if ($id > 0) $count_where['id'] = ['neq', $id];

            $count = Db::name('car')->where($count_where)->count();
            if ($count) adminReturn(2, '该车牌已存在');

            $data = [
                "img" => $img,
                "number" => $number,
                "model" => $model,
                "price" => $price,
            ];

            if ($id > 0) {
                $data['update_time'] = time();
                $res = Db::name('car')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('carList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $data['create_time'] = time();
                $res = Db::name('car')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('carList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('car')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '车辆');

            return $this->view->fetch();
        }
    }

    /**
     * 删除车辆
     * */
    public function delCar()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('car')->where(['id' => $id])->find();
        if ($info['user_id'] > 0) adminReturn(2, '车辆正在使用中，无法删除');

        if ($info) {
            $res = Db::name('car')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 上架/下架
     * */
    public function upperCar()
    {
        $id = Request()->param('id');
        $is_upper = Request()->param('is_upper');

        if (empty($id)) adminReturn(2, 'ID缺失');
        if ($is_upper != 1 && $is_upper != -1) adminReturn(2, '状态不正确');

        $info = Db::name('car')->where(['id' => $id])->find();
        if ($info['user_id'] > 0) adminReturn(2, '车辆正在使用中，操作失败');
        if ($info['team_user_id'] > 0) adminReturn(2, '车辆已被分配，操作失败');

        if ($info) {
            $data = [
                'is_upper' => $is_upper,
                'update_time' => time()
            ];
            $res = Db::name('car')->where(['id' => $id])->update($data);
            if ($res) {
                adminReturn(1, '操作成功');
            } else {
                adminReturn(2, '操作失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 投资意向审核列表
     * */
    public function applyList()
    {
        $input = Request()->param();

        $status = $input['status'];

        $where = [];
        if ($status) $where['status'] = $status;

        $list = Db::name('user_apply')->where($where)->order('id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '投资意向审核列表');
        return $this->view->fetch();
    }

    /**
     * 通过
     * */
    public function applyAgree()
    {
        $id = Request()->param('id');
        if (empty($id)) adminReturn(2, 'ID缺失');

        $data = [
            'status' => 2,
            'update_time' => time()
        ];
        $res = Db::name('user_apply')->where(['id' => $id])->update($data);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 驳回
     * */
    public function applyRefuse()
    {
        $id = Request()->param('id');
        if (empty($id)) adminReturn(2, 'ID缺失');

        $data = [
            'status' => -1,
            'update_time' => time()
        ];
        $res = Db::name('user_apply')->where(['id' => $id])->update($data);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 分配车辆
     * */
    public function allocateUserToCar()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $car_ids = $input['car_ids'];

        if (empty($user_id)) adminReturn(2, '用户ID缺失');

        Db::startTrans();
        try {
            if ($car_ids) {
                $car_data = [
                    'team_user_id' => $user_id,
                    'update_time' => time()
                ];
                $res = Db::name('car')->whereIn('id', $car_ids)->update($car_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '分配失败');
                }

                $wait_del = Db::name('user_team_car')->field('id,car_id')->where(['user_id' => $user_id, 'car_id' => ['not in', $car_ids]])->select();
                if ($wait_del) {
                    $wait_del_ids = array_column($wait_del, 'id');
                    $res = Db::name('user_team_car')->whereIn('id', $wait_del_ids)->delete();
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '分配失败');
                    }

                    $wait_del_car_ids = array_column($wait_del, 'car_id');
                    $res = Db::name('car')->whereIn('id', $wait_del_car_ids)->update(['team_user_id' => 0, 'update_time' => time()]);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '分配失败');
                    }
                }

                foreach ($car_ids as $v) {
                    $info = Db::name('user_team_car')->where(['user_id' => $user_id, 'car_id' => $v])->find();
                    if (!$info) {
                        $res = Db::name('user_team_car')->insert(['user_id' => $user_id, 'car_id' => $v, 'create_time' => time()]);
                        if (!$res) {
                            Db::rollback();
                            adminReturn(2, '分配失败');
                        }
                    }
                }
            } else {
                $res = Db::name('car')->where(['team_user_id' => $user_id])->update(['team_user_id' => 0, 'update_time' => time()]);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '分配失败');
                }

                $res = Db::name('user_team_car')->where(['user_id' => $user_id])->delete();
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '分配失败');
                }
            }

            Db::commit();
            adminReturn(1, '分配成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '分配失败' . $e->getMessage());
        }

    }

    /**
     * 收益核算
     * */
    public function profitLogList()
    {
        $list = Db::name('profit_log')->order('id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '收益核算');
        return $this->view->fetch();
    }

    /**
     * 文章列表
     * */
    public function articleList()
    {
        $list = Db::name('article')->order('id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '文章列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章
     * */
    public function doArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $title = $input['title'];
            $content = $input['content'];

            if (empty($title)) apiReturn(2, '请输入标题');
            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'title' => $title,
                'content' => $content
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('articleList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('articleList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('article')->where(['id' => $id])->find();
            }

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '文章');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章
     * */
    public function delArticle()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '文章ID缺失');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 权益福利
     * */
    public function vipArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $content = $input['content'];

            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'content' => $content
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('vip_article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('vipArticle'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('vip_article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('vipArticle'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = 1;

            if ($id > 0) {
                $info = Db::name('vip_article')->where(['id' => $id])->find();
            }

            $this->assign('title', '权益福利');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 用户须知
     * */
    public function userKnow()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $content = $input['content'];

            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'content' => $content
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('know_article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('userKnow'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('know_article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('userKnow'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = 1;

            if ($id > 0) {
                $info = Db::name('know_article')->where(['id' => $id])->find();
            }

            $this->assign('title', '用户须知');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 违章列表
     * */
    public function violationList()
    {
        $list = Db::name('violation_log')->order('id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '违章列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 违章
     * */
    public function doViolation()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $user_id = $input['user_id'];
            $car_id = $input['car_id'];
            $address = $input['address'];
            $time = $input['time'];
            $behavior = $input['behavior'];
            $according = $input['according'];
            $money = $input['money'];
            $score = $input['score'];
            $status = $input['status'];

            if (empty($user_id)) apiReturn(2, '请选择用户');
            if (empty($car_id)) adminReturn(2, '请选择车辆');

            $car_info = Db::name('car')->where(['id' => $car_id])->find();

            $number = $car_info['number'];
            $model = $car_info['model'];
            if (empty($number) || empty($model)) adminReturn(2, '请选择车辆');

            if (empty($address)) adminReturn(2, '请输入违章地点');
            if (empty($time)) adminReturn(2, '请输入违章时间');
            if (empty($behavior)) adminReturn(2, '请输入违章行为');
            if (empty($according)) adminReturn(2, '请输入依据');
            if (empty($money)) adminReturn(2, '请输入罚款金额');
            if (empty($score)) adminReturn(2, '请输入记分');

            $login_user_id = session('id');

            $data = [
                'user_id' => $user_id,
                'number' => $number,
                'model' => $model,
                'address' => $address,
                'time' => $time,
                'behavior' => $behavior,
                'according' => $according,
                'money' => $money,
                'score' => $score,
                'admin_user_id' => $login_user_id,
                'status' => $status
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = time();

                $res = Db::name('violation_log')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('violationList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = time();

                $res = Db::name('violation_log')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('violationList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('violation_log')->where(['id' => $id])->find();
            }

            $user_list = Db::name('user')->field('id,username,mobile')->where(['user_type' => 3])->select();
            $this->assign('user_list', $user_list);

            $car_list = Db::name('car')->field('id,number,model')->select();
            $this->assign('car_list', $car_list);

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '违章');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }


    /**
     * 删除违章
     * */
    public function delViolation()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '违章ID缺失');

        $info = Db::name('violation_log')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('violation_log')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 会员订单列表
     * */
    public function vipOrderList()
    {
        $payed_status = Request()->param('payed_status', 0);

        $where = [];
        if ($payed_status) $where['o.payed_status'] = $payed_status;

        $list = Db::name('vip_order o')->join('le_user u', 'o.user_id = u.id')
            ->field('o.*,u.username,u.mobile')
            ->where($where)
            ->order('o.id desc')
            ->paginate();

        $this->assign('list', $list);
        $this->assign('title', '会员订单列表');

        return $this->view->fetch();
    }


    /**
     * VIP付款凭证审核通过
     * */
    public function vipConfirmSuccess()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('vip_order')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $order_data = [
                    'payed_status' => 2,
                    'update_time' => time()
                ];
                $res = Db::name('vip_order')->where(['id' => $id])->update($order_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                $user_id = $info['user_id'];
                $up_user_id = Db::name('user')->where(['id' => $user_id])->value('up_user_id');

                $code = createSpreadCode();
                $data = [
                    'is_vip' => 1,
                    'code' => $code,
                    'update_time' => time()
                ];
                $res = Db::name('user')->where(['id' => $user_id])->update($data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                if ($up_user_id) {
                    $vip_price = $info['price'];
                    $commission_rate = C('COMMISSION_RATE');
                    $price = $vip_price * $commission_rate / 100;
                    if ($price > 0) {
                        $res = doProfit($up_user_id, $price, 'spread', $id, 'le_user', '来自推广收益', 1);
                        if (!$res) {
                            Db::rollback();
                            adminReturn(2, '操作失败');
                        }
                    }
                }

                Db::commit();

                // 生成海报
                $path = createPoster($user_id);
                if ($path) {
                    Db::name('user')->where('id', $user_id)->setField('app_poster', $path);
                }

                adminReturn(1, '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * VIP付款凭证审核失败
     * */
    public function vipConfirmFail()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('vip_order')->where(['id' => $id])->find();
        if ($info) {
            $data = [
                'payed_status' => -1,
                'update_time' => time()
            ];
            $res = Db::name('vip_order')->where(['id' => $id])->update($data);
            if ($res) {
                adminReturn(1, '操作成功');
            } else {
                adminReturn(2, '操作失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 预约列表
     * */
    public function slotList()
    {
        $list = Db::name('slot_order s')->join('le_user u', 's.user_id = u.id')
            ->field('s.id,u.username,u.mobile,s.order_id,s.is_end,s.create_time')
            ->order('s.order_id asc,s.is_end asc,s.id asc')
            ->paginate()->each(function ($val) {
                $order_info = Db::name('order')->where(['id' => $val['order_id']])->find();
                $val['number'] = $order_info['number'];
                $val['model'] = $order_info['model'];
                $val['price'] = $order_info['price'];

                return $val;
            });

        $this->assign('list', $list);
        $this->assign('title', '预约列表');

        return $this->view->fetch();
    }

    /**
     * 创建订单
     * */
    public function createOrder()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];            // 第一次选择车辆
            $car_id = $input['car_id'];
            $price = $input['price'];

            if (empty($id)) apiReturn(2, 'ID缺失');
            if (empty($car_id)) adminReturn(2, '请选择车辆');
            if ($price <= 0) apiReturn(2, '金额错误');

            $slot_order_info = Db::name('slot_order')->where(['id' => $id])->find();
            if (empty($slot_order_info)) adminReturn(2, '预约不存在');

            $user_id = $slot_order_info['user_id'];

            $car_info = Db::name('car')->where(['id' => $car_id])->find();
            if ($car_info['user_id'] > 0) adminReturn(2, '该车辆已被占用');

            $number = $car_info['number'];
            $model = $car_info['model'];
            if (empty($number) || empty($model)) adminReturn(2, '请选择车辆');

            Db::startTrans();
            try {
                $data = [
                    'order_sn' => date('YmdHis') . mt_rand(100000, 999999),
                    'user_id' => $user_id,
                    'car_id' => $car_id,
                    'number' => $number,
                    'model' => $model,
                    'price' => $price,
                    'create_time' => time()
                ];
                $order_id = Db::name('order')->insertGetId($data);
                if (!$order_id) {
                    Db::rollback();
                    adminReturn(2, '创建订单失败');
                }

                $data = [
                    'user_id' => $user_id,
                    'order_id' => $order_id,
                ];
                $res = Db::name('slot_order')->where(['id' => $id])->update($data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '创建订单失败');
                }

                Db::name('car')->where(['user_id' => $user_id])->setField('user_id', 0);
                Db::name('car')->where(['id' => $car_id])->setField('user_id', $user_id);

                Db::commit();
                adminReturn(1, '创建订单成功', url('AllOrderList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '创建订单失败');
            }
        } else {
            $input = Request()->param();

            $id = $input['id'];            // 第一次选择车辆

            $slot_order_info = Db::name('slot_order')->where(['id' => $id])->find();
            if (empty($slot_order_info)) adminReturn(2, '预约不存在');
            $this->assign('user_id', $slot_order_info['user_id']);

            //            $user_list = Db::name('user')->field('id,username,mobile')->where(['user_type' => 3])->select();
            //            $this->assign('user_list', $user_list);

            $car_list = Db::name('car')->field('id,number,model,price')->where(['is_upper' => 1, 'user_id' => 0])->select();
            $this->assign('car_list', $car_list);

            $this->assign('title', '选择车辆');

            return $this->view->fetch();
        }
    }

    /**
     * 重选车辆
     * */
    public function againChooseCar()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $car_id = $input['car_id'];
            $price = $input['price'];

            if (empty($id)) apiReturn(2, 'ID缺失');
            if (empty($car_id)) adminReturn(2, '请选择车辆');
            if ($price <= 0) apiReturn(2, '金额错误');

            $order_info = Db::name('order')->where(['id' => $id])->find();
            if (empty($order_info)) adminReturn(2, '订单不存在');

            $user_id = $order_info['user_id'];

            $car_info = Db::name('car')->where(['id' => $car_id])->find();
            if ($car_info['user_id'] > 0) adminReturn(2, '该车辆已被占用');

            $number = $car_info['number'];
            $model = $car_info['model'];
            if (empty($number) || empty($model)) adminReturn(2, '请选择车辆');

            Db::startTrans();
            try {
                $data = [
                    'car_id' => $car_id,
                    'number' => $number,
                    'model' => $model,
                    'price' => $price,
                    'update_time' => time()
                ];
                $res = Db::name('order')->where(['id' => $id])->update($data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '选择车辆失败');
                }

                Db::name('car')->where(['user_id' => $user_id])->setField('user_id', 0);
                Db::name('car')->where(['id' => $car_id])->setField('user_id', $user_id);

                Db::commit();
                adminReturn(1, '创建订单成功', url('AllOrderList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '创建订单失败');
            }
        } else {
            $input = Request()->param();

            $id = $input['id'];

            $order_info = Db::name('order')->where(['id' => $id])->find();
            if (empty($order_info)) adminReturn(2, '订单不存在');
            $this->assign('user_id', $order_info['user_id']);

            //            $user_list = Db::name('user')->field('id,username,mobile')->where(['user_type' => 3])->select();
            //            $this->assign('user_list', $user_list);

            $car_list = Db::name('car')->field('id,number,model,price')->where(['is_upper' => 1, 'user_id' => 0])->select();
            $this->assign('car_list', $car_list);

            $this->assign('title', '选择车辆');

            return $this->view->fetch('create_order');
        }
    }

    /**
     * 所有订单列表
     * */
    public function allOrderList()
    {
        $input = Request()->param();

        $user = $input['user'] ? : '';
        $car = $input['car'] ? : '';
        $start_date = $input['start_date'] ? : '';
        $end_date = $input['end_date'] ? : '';
        $status = $input['status'];

        $where = [];
        if ($user) $where['u.username|u.mobile'] = ['like', '%' . $user . '%'];
        if ($car) $where['o.number|o.model'] = ['like', '%' . $car . '%'];
        if ($start_date || $end_date) $where['o.pay_time'] = ['between', [$start_date, $end_date]];
        if ($status) $where['o.status'] = $status;

        $list = Db::name('order o')->join('le_user u', 'o.user_id = u.id')
            ->field('o.id,o.order_sn,o.number,o.model,o.price,o.status,o.start_time,o.end_time,o.pay_time,o.create_time,u.username,u.mobile')
            ->where($where)
            ->order('o.id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '订单列表');

        return $this->view->fetch();
    }

    /**
     * 付款凭证列表
     * */
    public function payedList()
    {
        $payed_status = Request()->param('payed_status');
        if ($payed_status != 0) $where['p.payed_status'] = $payed_status;

        $list = Db::name('order_payed p')->join('le_order o', 'p.order_id = o.id')
            ->field('p.*,o.number,o.model,o.price')
            ->where($where)
            ->order('p.id desc')
            ->paginate();

        $this->assign('list', $list);
        $this->assign('title', '付款凭证列表');

        return $this->view->fetch();
    }

    /**
     * 付款成功
     * */
    public function confirmPayedSuccess()
    {
        $id = Request()->param('id');

        if (empty($id)) apiReturn(2, 'ID缺失');

        $info = Db::name('order_payed')->where(['id' => $id])->find();

        if (empty($info)) adminReturn(2, '付款凭证不存在');
        if ($info['payed_status'] != 1) adminReturn(2, '付款凭证状态错误');

        $order_info = Db::name('order')->where(['id' => $info['order_id']])->find();
        if (empty($order_info)) {
            Db::rollback();
            adminReturn(2, '订单不存在');
        }

        $time = time();

        $start_time = ($order_info['start_time'] ? strtotime($order_info['start_time']) : $time);
        $end_time = ($order_info['end_time'] ? strtotime($order_info['end_time']) : $time) + 3600 * 24;

        Db::startTrans();
        try {
            $order_data = [
                'status' => 2,
                'start_time' => date('Y-m-d H:i:s', $start_time),
                'end_time' => date('Y-m-d H:i:s', $end_time),
                'pay_time' => $time,
                'update_time' => $time
            ];
            $count = Db::name('order_payed')->where(['order_id' => $info['order_id']])->count();

            if ($count > 1) {
                // 续费
                $order_data['type'] = 2;
            } else {
                // 新开
                /*$user_order_count = Db::name('order')->where(['user_id' => $order_info['user_id']])->count();
                if ($user_order_count == 1) {
                    // 首单
                    $up_user_id = Db::name('user')->where(['id' => $order_info['user_id']])->value('up_user_id');
                    if ($up_user_id > 0) {
                        $res = doProfit($up_user_id, $order_info['price'] * C('COMMISSION_RATE') / 100, 'spread', $info['order_id'], 'le_order', '来自租车缴费收益', 1);
                        if (!$res) {
                            Db::rollback();
                            adminReturn(2, '操作失败');
                        }
                    }
                }*/
            }

            // 绑定车辆
            $car_info = Db::name('car')->where(['id' => $order_info['car_id']])->find();
            if ($car_info['user_id'] == $order_info['user_id'] && $car_info['is_upper'] == 1) {
                $car_data = [
                    'user_id' => $order_info['user_id'],
                    'all_profit' => $car_info['all_profit'] + $order_info['price'],
                    'update_time' => $time
                ];
                $res = Db::name('car')->where(['id' => $order_info['car_id']])->update($car_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }
            } else {
                Db::rollback();
                adminReturn(2, '车辆已下架或已被使用');
            }

            // 车队车辆信息修改
            $user_team_car_info = Db::name('user_team_car')->where('car_id', $order_info['car_id'])->find();
            if ($user_team_car_info) {
                $team_user_car_data = [
                    'all_profit' => $user_team_car_info['all_profit'] + $order_info['price'],
                    'start_date' => date('Y-m-d', $start_time),
                    'end_date' => date('Y-m-d', $end_time),
                    'status' => 2,
                    'update_time' => $time
                ];
                $res = Db::name('user_team_car')->where('car_id', $order_info['car_id'])->update($team_user_car_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                // 投资者收益
                $res = doProfit($user_team_car_info['user_id'], $order_info['price'] * C('COO_RATE') / 100, 'invest_lease_car', $info['order_id'], 'le_order', '来自租车缴费收益');
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }
            }

            $res = Db::name('order')->where(['id' => $info['order_id']])->update($order_data);
            if (!$res) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }

            $payed_data = [
                'payed_status' => 2,
                'update_time' => $time
            ];
            $res = Db::name('order_payed')->where(['id' => $id])->update($payed_data);
            if (!$res) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }

            // 结束订单
            $jobHandlerClassName = 'app\index\job\JobOrder';                     // 任务执行类
            $jobQueueName = 'lease_end';                                         // 队列名称
            $jobData = ['order_id' => $id];                                      // 传给任务的数据

            $delay = $end_time - time();
            Queue::later($delay, $jobHandlerClassName, $jobData, $jobQueueName);

            // 租赁即将到期
            $remind_jobHandlerClassName = 'app\index\job\Remind';                // 任务执行类
            $remind_jobQueueName = 'remind';                                     // 队列名称
            $remind_jobData = ['order_id' => $id];                               // 传给任务的数据

            $remind_delay = $end_time - time() - C('LATER_TIME') * 60;
            Queue::later($remind_delay, $remind_jobHandlerClassName, $remind_jobData, $remind_jobQueueName);

            Db::commit();
            adminReturn(1, '操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '操作失败' . $e->getMessage());
        }

    }

    /**
     * 付款失败
     * */
    public function confirmPayedFail()
    {
        $id = Request()->param('id');

        if (empty($id)) apiReturn(2, 'ID缺失');

        $info = Db::name('order_payed')->where(['id' => $id])->find();

        if (empty($info)) adminReturn(2, '付款凭证不存在');
        if ($info['payed_status'] != 1) adminReturn(2, '付款凭证状态错误');

        $data = [
            'payed_status' => -1,
            'update_time' => time()
        ];
        $res = Db::name('order_payed')->where(['id' => $id])->update($data);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 开始计时
     * */
    public function startTiming()
    {
        $id = Request()->param('id');

        if (empty($id)) apiReturn(2, 'ID缺失');

        $info = Db::name('order')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '订单不存在');

        if ($info['status'] != 2) adminReturn(2, '订单状态错误');

        $start_time = time();
        $end_time = $start_time + 3600 * 24;

        $data = [
            'start_time' => date('Y-m-d H:i:s', $start_time),
            'end_time' => date('Y-m-d H:i:s', $end_time),
            'update_time' => $start_time
        ];

        $res = Db::name('order')->where(['id' => $id])->update($data);
        if ($res) {
            // 结束订单
            $jobHandlerClassName = 'app\index\job\JobOrder';                     // 任务执行类
            $jobQueueName = 'lease_end';                                         // 队列名称
            $jobData = ['order_id' => $id];                                      // 传给任务的数据

            $delay = $end_time - time();
            Queue::later($delay, $jobHandlerClassName, $jobData, $jobQueueName);

            // 租赁即将到期
            $remind_jobHandlerClassName = 'app\index\job\Remind';                // 任务执行类
            $remind_jobQueueName = 'remind';                                     // 队列名称
            $remind_jobData = ['user_id' => $info['user_id']];                   // 传给任务的数据

            $remind_delay = $end_time - time() - C('LATER_TIME') * 60;
            //            $remind_delay = 5;
            Queue::later($remind_delay, $remind_jobHandlerClassName, $remind_jobData, $remind_jobQueueName);

            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 到期订单列表
     * */
    public function remindOrderList()
    {
        $input = Request()->param();

        $user = $input['user'] ? : '';
        $car = $input['car'] ? : '';
        $start_date = $input['start_date'] ? : '';
        $end_date = $input['end_date'] ? : '';

        $where['o.is_remind'] = 1;
        $where['o.status'] = ['IN', [2, 3]];
        if ($user) $where['u.username|u.mobile'] = ['like', '%' . $user . '%'];
        if ($car) $where['o.number|o.model'] = ['like', '%' . $car . '%'];
        if ($start_date || $end_date) $where['o.pay_time'] = ['between', [$start_date, $end_date]];

        $list = Db::name('order o')->join('le_user u', 'o.user_id = u.id')
            ->field('o.id,o.order_sn,o.number,o.model,o.price,o.status,o.start_time,o.end_time,o.pay_time,o.create_time,u.username,u.mobile')
            ->where($where)
            ->order('o.id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '到期订单列表');

        return $this->view->fetch();
    }

    /**
     * 支付配置
     * */
    public function setPay()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $pay_type = $input['pay_type'] ? : 1;// 1：二维码收款，2：在线支付
            $pay_img = $input['pay_img'] ? : '';
            $pay_vip_img = $input['pay_vip_img'] ? : '';

            Db::startTrans();
            try {
                Db::name('config')->where(['name' => 'PAY_TYPE'])->setField('value', $pay_type);
                Db::name('config')->where(['name' => 'PAY_IMG'])->setField('value', $pay_img);
                Db::name('config')->where(['name' => 'PAY_VIP_IMG'])->setField('value', $pay_vip_img);

                Db::commit();

                Cache::clear();

                adminReturn(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '保存失败');
            }
        } else {
            $this->assign('pay_type', C('PAY_TYPE'));
            $this->assign('pay_img', C('PAY_IMG'));
            $this->assign('pay_vip_img', C('PAY_VIP_IMG'));

            $this->assign('title', '支付配置');
            return $this->view->fetch();
        }
    }
}
